package com.flying.cms.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.flying.common.annotation.CommonQuery;
import com.flying.common.annotation.CommonUpdate;
import com.flying.common.annotation.CommonUpdate.Position;
import com.flying.common.util.Codes;
import com.flying.common.util.StringUtils;
import com.flying.framework.context.ServiceContext;
import com.flying.framework.data.Data;
import com.flying.framework.service.AbstractService;

public class ContentService  extends AbstractService{
	private final static DateFormat df = new SimpleDateFormat("yyyyMMddHH");
	private final static DateFormat ldf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
	
	//@RemoveCache(tag="cms.Content")
	@CommonUpdate( position=Position.after_body,
			usql="insert into t_content(content_id, category_id, "
					+ "title, summary, content, tag, tag2, sort_id, status, publish_date, "
					+ "icon, icon2, icon3, icon4, link, source, "
					+ "f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, "
					+ "creator, create_date, update_date) "+
				"values(?,?,"
					+ "?,?,?,?,?,?,0, ?, "
					+ "?,?,?,?,?,?, "
					+ "?,?,?,?,?,?,?,?,?,?,"
					+ "?,now(), now())",
			params={"$SEQ.CMS.CONTENT", "category_id", 
					"title", "summary", "content","tag", "tag2", "sort_id:0", "publish_date", 
					"icon", "icon2", "icon3", "icon4", "link", "source", 
					"f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9" ,
					"creator"})
	public Data create(Data request) throws Exception {
		request.remove(Codes.CODE);
		if(!StringUtils.isEmpty(request.getString("publish_date"))) {
			Date pd = ldf.parse(request.getString("publish_date"));
			request.put("publish_date", pd);
			request.put("tag2", df.format(pd));
		} else {
			request.put("publish_date", null);
			request.put("tag2", null);
		}
		if(request.getStrings("tag") != null) {
			String tags[] = request.getStrings("tag");
			String tmps = "";
			for(String t: tags) {
				if(tmps.equals("")) {
					tmps = t;
				} else {
					tmps = tmps + "," + t;
				}
				request.put("tag", tmps);
			}
		}
		return request;
	}

	//@RemoveCache(tag="cms.Content")
	@CommonUpdate(position=Position.after_body, 
				usql="update t_content "+
				"set category_id=?, "
				+ "title=?, summary=?, content=?, tag=?, tag2=?, sort_id=?, status=0, "
				+ "icon=?, icon2=?, icon3=?, icon4=?, link=?, source=?, "
				+ "f0=?, f1=?, f2=?, f3=?, f4=?, f5=?, f6=?, f7=?, f8=?, f9=?, "
				+ "publish_date=?, update_date=now(), updator=? "+
				"where content_id=?",
			params={"category_id", 
				"title", "summary", "content","tag", "tag2", "sort_id:0", 
				"icon", "icon2", "icon3", "icon4", "link", "source", 
				"f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", 
				"publish_date", "updator",
				"content_id"})
	public Data update(Data request) throws Exception {
		Data c = this.findById(request);
		if(c != null) {
			for(int i=0; i < 4; i++) {
				final String fn = "icon"+(i == 0?"":String.valueOf(i + 1));
				final String fv = request.getString(fn);
				if(StringUtils.isEmpty(fv) )
					request.put(fn, c.getString(fn));
			}
			for(int i=0; i < 10; i++) {
				final String fn = "f" + String.valueOf(i);
				final String fv = request.getString(fn);
				if(StringUtils.isEmpty(fv) )
					request.put(fn, c.getString(fn));
			}
		}
		//
		if(!StringUtils.isEmpty(request.getString("publish_date"))) {
			Date pd = ldf.parse(request.getString("publish_date"));
			request.put("publish_date", pd);
			request.put("tag2", df.format(pd));
		} else {
			request.put("publish_date", null);
			request.put("tag2", null);
		}
		if(request.getStrings("tag") != null) {
			String tags[] = request.getStrings("tag");
			String tmps = "";
			for(String t: tags) {
				if(tmps.equals("")) {
					tmps = t;
				} else {
					tmps = tmps + "," + t;
				}
				request.put("tag", tmps);
			}
		}
		request.remove(Codes.CODE);
		return request;
	}

	//@RemoveCache(tag="cms.Content")
	@CommonUpdate(position=Position.after_body, 
			usql="update t_content set status=1, publisher=?, update_date=now() where status != 1 and content_id=?",
			params={"publisher", "content_id"})
	public Data publish(Data request) throws Exception {
		if(ServiceContext.getContext() != null && ServiceContext.getContext().getPrincipal() != null) {
			request.put("publisher", ServiceContext.getContext().getPrincipal().getName());
		}
		return request;
	}

	//@RemoveCache(tag="cms.Content")
	@CommonUpdate(usql="update t_content set status=0, publisher=null where content_id=?",
			params={"content_id"})
	public Data unpublish(Data request) throws Exception {
		return request;
	}
	
	@CommonUpdate(usql="update t_content set browsers=(case when browsers is null then 0 else browsers end)+1 where content_id=?", params={"content_id"})
	public Data reads(Data request) throws Exception {
		return request;
	}

	@CommonQuery(position=CommonQuery.Position.after_body, 
			single=true, qsql="select * from t_content where content_id=?", 
			params={"content_id"})
	public Data findById(Data request) throws Exception {
		request.remove(Codes.CODE);
		return request;
	}

	@CommonQuery(position=CommonQuery.Position.after_body, 
			single=true, 
			qsql="select * from t_content where content_id=? and status=1", 
			params={"content_id"})
	public Data findPublishedContentById(Data request) throws Exception {
		request.remove(Codes.CODE);
		reads(request);
		return request;
	}
	
	@CommonQuery(params={"category_id", "words", "words"})
	public Data findByCategoryId(Data request) throws Exception {
		return request;
	}

	public Data findByCategoryId2(Data request) throws Exception {
		if(request.getString("words") == null) {
			request.put("words", "");
		}
		Data data = findByCategoryId(request);
		List<Map> rows = data.get("rows");
		for(Map m: rows) {
			String tag = (String)m.get("tag");
			String[] tags = StringUtils.split(tag, ",");
			m.put("tag", tags);
		}
		return data;
	}

	//@UseCache(tag="cms.Content", keys={"code", "page", "rows"})
	@CommonQuery(params={"code"})
	public Data findByCategoryCode(Data request) throws Exception {
		return request;
	}

	public Data findByCategoryCodeAsRows(Data request) throws Exception {
		return new Data(Codes.CODE, Codes.SUCCESS, "rows", findByCategoryCode(request).get("rows"), "$value", "rows");
	}

	//@UseCache(tag="cms.Content", keys={"code","tag", "page", "rows"})
	@CommonQuery(params={"code","tag"})
	public Data findByCategoryCodeAndTag(Data request) throws Exception {
		return request;
	}

	//@UseCache(tag="cms.Content", keys={"tag", "page", "rows"})
	@CommonQuery(params={"tag"})
	public Data findByTag(Data request) throws Exception {
		return request;
	}

	//@UseCache(tag="cms.Content", keys={"tag2", "page", "rows"})
	@CommonQuery(params={"tag2"})
	public Data findByTag2(Data request) throws Exception {
		return request;
	}

	//@UseCache(tag="cms.Content", keys={"code","tag", "page", "rows"})
	@CommonQuery(params={"code","tag"})
	public Data findByCategoryCodeAndTag2(Data request) throws Exception {
		return request;
	}

	@CommonQuery(params={"code","code"})
	public Data findAllByCategoryCode(Data request) throws Exception {
		return request;
	}

	//@RemoveCache(tag="cms.Content")
	@CommonUpdate(usql="update t_content set del_flag=1 where content_id=?", params={"content_id"})
	public Data remove(Data request) throws Exception {
		return request;
	}

	//@RemoveCache(tag="cms.Content")
	@CommonUpdate(usql="update t_content set del_flag=0 where content_id=?", params={"content_id"})
	public Data unremove(Data request) throws Exception {
		return request;
	}

	@CommonQuery(position=CommonQuery.Position.after_body, 
		qsql="select * from t_content where status=0 and tag2=? limit ?,? ", 
		csql="select count(0) from t_content where status=0 and tag2=? ", 
		params={"tag2"})
	public Data findUnpublished(Data request) throws Exception {
		return request;
	}

	@SuppressWarnings("rawtypes")
	public Data publishAtTheDate(Data request) throws Exception {
		final String tag2 = df.format(new Date());
		List<Map> unpublished = this.findUnpublished(new Data("tag2", tag2, "page", 1, "rows", 50)).get("rows");
		for(Map d: unpublished) {
			this.publish(new Data("content_id", (Integer)d.get("content_id")));
		}
		final int rowCount = unpublished.size();
		return new Data(Codes.CODE, Codes.SUCCESS, "rows", rowCount);
	}
	
	//@UseCache(tag="cms.Content", keys={"page", "rows"})
	@CommonQuery(params={})
	public Data findAll(Data request) throws Exception {
		return request;
	}

	//@UseCache(tag="cms.Content", keys={"page", "rows"})
	@CommonQuery(params={})
	public Data findRemoves(Data request) throws Exception {
		return request;
	}

	public Data thrift(Data request) throws Exception {
		return request;
	}
}
